package com.witmore.neutron.ai.web.apiv2.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.db.entity.AgentDeploymentDO;
import com.witmore.neutron.ai.db.mapper.AgentDeploymentMapper;
import com.witmore.neutron.ai.web.annotation.RequiresPermission;
import com.witmore.neutron.ai.web.controller.vo.*;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.AgentDeploymentService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * V2 智能体部署相关接口
 *
 * @author 豆子高
 * @date 2025-09-17
 */
@Slf4j
@RestController
@RequestMapping("/v2/agent/deployment")
public class AgentDeploymentControllerV2 {

    @Autowired
    private AgentDeploymentService agentDeploymentService;

    @Autowired
    private AgentDeploymentMapper agentDeploymentMapper;


    /**
     * 部署智能体
     */
    @RequiresPermission("agent:deploy")
    @PostMapping("/deploy")
    public ResponseResult<Void> deployAgent(@Valid @RequestBody AgentDeploymentRequest request) {
        try {
            agentDeploymentService.deployAgentWithConfig(request);
            return ResponseResult.success();
        } catch (Exception e) {
            log.error("部署智能体失败", e);
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    /**
     * 根据编码获取部署信息
     */
    @RequiresPermission("agent:deploy:view")
    @GetMapping("/info/{agentCode}")
    public ResponseResult<AgentDeploymentResponse> getDeploymentInfo(@PathVariable String agentCode) {
        try {
            AgentDeploymentDO deployment = agentDeploymentMapper.selectOne(new LambdaQueryWrapper<AgentDeploymentDO>()
                    .eq(AgentDeploymentDO::getAgentCode, agentCode));
            if (deployment == null) {
                return ResponseResult.fail(1001, "部署信息不存在");
            }
            return ResponseResult.success(AgentDeploymentResponse.fromEntity(deployment));
        } catch (Exception e) {
            log.error("获取部署信息失败", e);
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    /**
     * 切换部署状态（发布/下架）
     */
    @RequiresPermission("agent:deploy:status")
    @PostMapping("/toggle-status/{agentCode}")
    public ResponseResult<Void> toggleDeploymentStatus(@PathVariable String agentCode, @Valid @RequestBody ToggleDeploymentStatusRequest request) {
        try {
            if (request.getDeployStatus() == null || (request.getDeployStatus() != 1 && request.getDeployStatus() != 2)) {
                return ResponseResult.fail(1001, "部署状态参数错误，只能是1（已部署）或2（停用）");
            }
            agentDeploymentService.toggleDeploymentStatus(agentCode, request.getDeployStatus());
            return ResponseResult.success();
        } catch (Exception e) {
            log.error("切换部署状态失败", e);
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    /**
     * 获取用户的部署列表
     */
    @RequiresPermission("agent:deploy:list")
    @GetMapping("/list")
    public ResponseResult<List<AgentDeploymentResponse>> getUserDeployments() {
        try {
            List<AgentDeploymentDO> deployments = agentDeploymentMapper.selectList(
                    new LambdaQueryWrapper<AgentDeploymentDO>()
                            .eq(AgentDeploymentDO::getUserId, GlobalAccountSession.getUserInfo().getId())
                            .orderByDesc(AgentDeploymentDO::getCreateTime)
            );

            return ResponseResult.success(deployments.stream()
                    .map(AgentDeploymentResponse::fromEntity)
                    .toList());
        } catch (Exception e) {
            log.error("获取部署列表失败", e);
            return ResponseResult.fail(500, e.getMessage());
        }
    }

}
